from nicegui import ui, app

import pwd
import subprocess
import time
import datetime
# 用户数据库
users = {
    "admin": "password123",
    "user": "user123"
}

def get_all_users():
    """获取系统中所有用户"""
    users = []
    try:
        for user in pwd.getpwall():
            users.append(user.pw_name)
        return users
    except Exception as e:
        print(f"获取用户列表失败: {e}")
        return []



def execute_command():
    """执行Linux命令"""
    command = command_input.value.strip()
    if not command:
        ui.notify("请输入命令", type='warning')
        return

    # 使用示例
    all_users = get_all_users()
    if len(all_users) <= 0:
        ui.notify("获取用户失败", type='warning')
        return

    print(command_input.value)
    print(type(command))
    print(command.split("\r\n"))
    all_command = command.splitlines()
    all_command_s = []
    for i in range(len(all_command)):
        ss = all_command[i]
        # print(ss.split(' '))
        name_pass = ss.split()
        if len(name_pass) != 2:
            ui.notify("格式错误", type='warning')
            return
        if name_pass[0] not in all_users:
            ui.notify(f"{name_pass[0]}用户不存在", type='warning')
            return
        all_command_s.append(name_pass)

    print(all_command_s)
    for cmd in all_command_s:
        try:
                    # 构建命令
            ch_cmd = f"echo '{cmd[0]}:{cmd[1]}' | chpasswd"
            # 执行命令并获取输出
            result = subprocess.run(ch_cmd, shell=True, capture_output=True, text=True, timeout=30)

            if result.returncode == 0:
                output_text.value += result.stdout
                ui.notify("命令执行成功", type='positive')
            else:
                output_text.value += f"错误: {result.stderr}\n返回码: {result.returncode}"
                ui.notify("命令执行失败", type='negative')

        except subprocess.TimeoutExpired:
            output_text.value += "命令执行超时"
            ui.notify("命令执行超时", type='warning')
        except Exception as e:
            output_text.value += f"执行错误: {str(e)}"
            ui.notify(f"执行错误: {str(e)}", type='negative')
        output_text.value += f"\n===============================================\n"

def handle_file_upload(event):
    print(event)
    """处理文件上传"""
    if event.content:
        try:
            content = event.content.read().decode('utf-8')
            command_input.value = content
            ui.notify("文件加载成功", type='positive')
        except Exception as e:
            ui.notify(f"文件读取失败: {str(e)}", type='negative')


@ui.page('/')
def login_page():
    # 如果已经登录，直接跳转到主页
    if app.storage.user.get('authenticated', False):
        ui.navigate.to('/main')
        return

    def try_login():
        username = username_input.value
        password = password_input.value

        if users.get(username) == password:
            # 存储用户信息到 app.storage.user
            app.storage.user['authenticated'] = True
            app.storage.user['username'] = username
            app.storage.user['login_time'] =  datetime.datetime.now().isoformat()  # 登录时间

            ui.notify('登录成功！', type='positive')
            ui.navigate.to('/main')
        else:
            ui.notify('用户名或密码错误', type='negative')

    with ui.column().classes('absolute-center items-center'):
        ui.label('系统登录').classes('text-2xl font-bold mb-4')

        with ui.card().classes('w-80 p-6'):
            username_input = ui.input('用户名').classes('w-full mb-4')
            password_input = ui.input('密码', password=True, password_toggle_button=True).classes('w-full mb-4')

            ui.button('登录', on_click=try_login).classes('w-full')

@ui.page('/main')
def main_page():
    # 检查登录状态
    if not app.storage.user.get('authenticated', False):
        ui.navigate.to('/')
        return

    # 获取用户信息
    username = app.storage.user.get('username', '未知用户')
    login_time = app.storage.user.get('login_time', '未知时间')

    def logout():
        # 清除用户存储
        app.storage.user.clear()
        ui.navigate.to('/')

    with ui.column().classes('w-full max-w-4xl mx-auto p-4'):
            # 顶部导航
            with ui.row().classes('w-full justify-between items-center mb-6'):
                with ui.avatar():
                    ui.image('https://robohash.org/robot?bgset=bg2')
                # ui.avatar('img:https://nicegui.io/logo_square.png', color='blue-2')
                ui.label(f' {username}').classes('text-xl font-bold')
                ui.label(f'登录时间：{login_time}').classes('text-xl font-bold')
                ui.button('退出登录', on_click=logout, icon='logout').classes('bg-red-500 text-white')

            # 命令输入区域
            with ui.card().classes('w-full p-4'):
                ui.label('输入Linux命令').classes('text-lg font-bold mb-2')

                global command_input
                command_input = ui.textarea('请输入命令（支持多行）') \
                    .classes('w-full') \
                    .style('min-height: 150px; resize: both;') \
                    .props('outlined auto-grow')

                # 文件上传
                with ui.row().classes('w-full items-center gap-4 mt-4'):
                    ui.upload(
                        label='上传TXT文件',
                        on_upload=handle_file_upload,
                        auto_upload=True
                    ).classes('flex-grow')

                    ui.button('清空输入', on_click=lambda: setattr(command_input, 'value', ''), icon='clear') \
                        .classes('bg-gray-500 text-white')

                ui.button('执行命令', on_click=execute_command, icon='play_arrow') \
                    .classes('bg-blue-500 text-white mt-4')

            # 输出显示区域
            with ui.card().classes('w-full p-4 mt-4'):
                ui.label('命令输出').classes('text-lg font-bold mb-2')

                global output_text
                output_text = ui.textarea('输出将显示在这里') \
                    .classes('w-full') \
                    .style('min-height: 200px; resize: both;') \
                    .props('readonly outlined auto-grow')

                # 输出区域操作按钮
                with ui.row().classes('w-full justify-end gap-2 mt-2'):
                    ui.button('清空输出', on_click=lambda: setattr(output_text, 'value', ''), icon='clear') \
                        .classes('bg-gray-500 text-white')
                    ui.button('复制输出', on_click=lambda: ui.run_javascript(f'navigator.clipboard.writeText(`{output_text.value}`)'), icon='content_copy') \
                        .classes('bg-green-500 text-white')

if __name__ in ["__main__", "__mp_main__"]:
    ui.run(
        title="用户登录系统",
        port=9090,
        favicon="⚡",
        storage_secret="your-secure-secret-key-here",  # 必须设置
        dark=True
    )
